<template>
    <div class="home-wrap">
        <div class="desktop-layout-pc">
            <div class="desktop-top-bar">
                <div class="desktop-top-bar-left">
                    <span class="desktop-logo-pc">{{ projectTitle }}</span>
                </div>
                <div class="desktop-top-bar-right">
                    <div class="desktop-search-input-pc">
                        <el-input v-model="tableModel.searchParams.title" class="search-input" :prefix-icon="Search" placeholder="搜索文档、模板、文库" @keyup.enter="tableModel.fetchProposals"/>
                    </div>
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            <el-avatar :size="35" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" style="margin-right: 10px;"></el-avatar>
                            <span class="user-name">管理员</span>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item @click="exit">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>

            <div class="desktop-layout-inner-pc">
                <div class="desktop-layout-sidebar-pc">
                    <nav class="desktop-sidebar">
                        <div class="nav-btn">
                            <el-button class="btn" type="primary" @click="proposalModel.addProposal(0)">
                                <CirclePlusFilled class="icon" />
                                新建文档
                            </el-button>
                            <el-button class="btn" type="default" @click="importModel.importProposal">
                                <el-icon class="icon"><i class="iconfont icon-daoru"></i></el-icon>
                                导入文档
                            </el-button>
                        </div>

                        <el-menu class="nav-menu">
                            <el-menu-item index="home" @click="clickMenu('home')">
                                <HomeFilled class="icon" />
                                <span>首页</span>
                            </el-menu-item>
                            <el-sub-menu index="docs">
                                <template #title>
                                    <Menu class="icon" />
                                    <el-dropdown>
                                        <span class="menu-label">我的文档</span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item>
                                                    <el-button link size="small" @click="proposalModel.addProposal(0)">新建文档</el-button>
                                                </el-dropdown-item>
                                                <el-dropdown-item>
                                                    <el-button link size="small" @click="folderModel.addFolder(0)">新建文件夹</el-button>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </template>
                                <el-tree class="tree-menu" :data="folderList" :props="folderModel.folderProps" @node-click="clickMenu">
                                    <template #default="{ node, data }">
                                        <div class="tree-node">
                                            <Folder class="icon" style="margin-right: 3px;" />
                                            <el-dropdown>
                                                <span class="tree-node-label">{{ node.label }}</span>
                                                <template #dropdown>
                                                    <el-dropdown-menu>
                                                        <el-dropdown-item>
                                                            <el-button link size="small" @click="proposalModel.addProposal(data.id)">新建文档</el-button>
                                                        </el-dropdown-item>
                                                        <el-dropdown-item>
                                                            <el-button link size="small" @click="folderModel.addFolder(data.id)">新建文件夹</el-button>
                                                        </el-dropdown-item>
                                                        <el-dropdown-item>
                                                            <el-button link size="small" @click="folderModel.deleteFolder(data.id)">删除文件夹</el-button>
                                                        </el-dropdown-item>
                                                    </el-dropdown-menu>
                                                </template>
                                            </el-dropdown>
                                        </div>
                                    </template>
                                </el-tree>
                            </el-sub-menu>
                            <el-menu-item index="recycle"  @click="clickMenu('recycle')">
                                <DeleteFilled class="icon" />
                                <span>回收站</span>
                            </el-menu-item>
                        </el-menu>
                    </nav>
                </div>

                <div class="desktop-layout-main-pc">
                    <div class="m-header">
                        <span>我的文档</span>
                    </div>
                    <div class="m-body">
                        <el-table class="m-table" :data="tableModel.tableData" stripe style="width: 100%;height: 92%;" size="large">
                            <el-table-column fixed prop="title" label="标题" min-width="200">
                                <template #default="scope">
                                    <svg t="1750233752518" style="margin-right: 8px;vertical-align: -4px;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6460" width="18" height="18"><path d="M146.863158 0h538.947368l296.421053 296.421053v619.789473c0 59.284211-48.505263 107.789474-107.789474 107.789474H146.863158c-59.284211 0-107.789474-48.505263-107.789474-107.789474V107.789474c0-59.284211 48.505263-107.789474 107.789474-107.789474z" fill="#2F77F1" p-id="6461"></path><path d="M688.505263 0l296.421053 296.421053h-296.421053V0zM549.726316 661.557895H142.821053c-14.821053 0-25.6-12.126316-25.6-25.6V633.263158c0-14.821053 12.126316-25.6 25.6-25.6h406.905263c13.473684 0 25.6 12.126316 25.6 25.6v2.694737c0 13.473684-10.778947 25.6-25.6 25.6z m-134.736842-350.31579H142.821053c-14.821053 0-25.6-10.778947-25.6-25.6V282.947368c0-14.821053 12.126316-25.6 25.6-25.6h272.168421c13.473684 0 25.6 12.126316 25.6 25.6v2.694737c0 13.473684-10.778947 25.6-25.6 25.6z m-272.168421 121.263158h245.221052c13.473684 0 25.6 12.126316 25.6 25.6v2.694737c0 13.473684-12.126316 25.6-25.6 25.6H142.821053c-14.821053 0-25.6-10.778947-25.6-25.6V458.105263c0-14.821053 12.126316-25.6 25.6-25.6z" fill="#AFFCFE" p-id="6462"></path></svg>
                                    <span class="title" @click="toEditor(scope.row.id)">{{ scope.row.title }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="industry" label="行业" />
                            <el-table-column prop="folderName" label="位置">
                                <template #default="scope">
                                    <span>{{ !scope.row.folderName ? '--' : scope.row.folderName }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="updateAt" label="日期">
                                <template #default="scope">
                                    <span>{{ scope.row.updateAt ? new Date(scope.row.updateAt).toLocaleDateString() : '--' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="words" label="字数" />
                            <el-table-column fixed="right" label="" width="80">
                            <template #default="scope">
                                <el-dropdown>
                                    <span style="font-size: 18px;cursor: pointer;">
                                        ...
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item :icon="Delete">
                                                <el-button link  size="small" @click="tableModel.docDelete(scope.row)">删除</el-button>
                                            </el-dropdown-item>
                                            <template v-if="menuStatus != 'recycle'">
                                                <el-dropdown-item :icon="Download">
                                                    <el-button link size="small" @click="tableModel.docDownload(scope.row)">下载</el-button>
                                                </el-dropdown-item>
                                                <el-dropdown-item :icon="EditPen">
                                                    <el-button link size="small" @click="renameModel.renameDoc(scope.row)">重命名</el-button>
                                                </el-dropdown-item>
                                            </template>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>


                <div class="desktop-panel">
                    <div class="m-header">
                        <span>工具箱</span>
                    </div>
                    <div class="b-body">
                        <div class="tools-panel">
                            <div class="tools-title">常用工具</div>
                            <div class="tools">
                                <div class="tool-item" v-for="item in toolsModel.tools" @click="toolsModel.toPage(item.path)">
                                    <Folder class="icon" />
                                    <span>{{ item.name }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="tools-panel">
                            <div class="tools-title">AI工具</div>
                            <div class="tools">
                                <div class="tool-item" v-for="item in toolsModel.tools" @click="toolsModel.toPage(item.path)">
                                    <Folder class="icon" />
                                    <span>{{ item.name }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新建方案对话框 -->
        <el-dialog v-model="proposalModel.dialogVisible" title="新建方案" width="520">
            <!-- 写一个新建方案的表单，最上面为 标准模式和模板模式选项，下面包含方案名称，方案类型，和方案prompt文本框 -->
            <el-radio-group  class="proposal-mode-selector" v-model="proposalModel.mode"  text-color="#626aef" fill="rgb(239, 240, 253)" @change="proposalModel.proposalModeChange">
                <el-radio-button label="standard">快速创建</el-radio-button>
                <el-radio-button label="template">从模板创建</el-radio-button>
            </el-radio-group>

            <el-form :model="proposalModel.form" :rules="proposalModel.proposalRules" ref="proposalFormRef" label-width="90px":label-position="'top'">
                <el-form-item label="方案名称" prop="title">
                    <el-input v-model="proposalModel.form.title" maxlength="20" show-word-limit placeholder="请输入唯一的方案名称" />
                </el-form-item>
                <el-form-item label="所属行业" prop="industry">
                    <el-select v-model="proposalModel.form.industry" placeholder="请选择行业">
                        <el-option v-for="item in industryList" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择模板" prop="templateId" v-if="proposalModel.mode === 'template'">
                    <el-select v-model="proposalModel.form.templateId" placeholder="请选择模板" ref="pTemplateSelectRef" @click.native="pTemplateModel.pTemplateHandleClick">
                        <el-option v-for="item in pTemplateModel.tempTypeList" :label="item.name" :value="item.id" :key="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="提示词" prop="prompt">
                    <el-input v-model="proposalModel.form.prompt" maxlength="3000" placeholder="请输入提示词" ref="promptInputRef" @click="pInputModel.inputHandleFocus" />
                </el-form-item>
                <el-form-item label="方案需求" prop="query">
                    <el-input v-model="proposalModel.form.query" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请描述方案的具体需求，描述越详细，生成越精准"/>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="proposalModel.cancelProposal">取消</el-button>
                    <el-button type="primary" :loading="proposalModel.genLoading" @click="proposalModel.confirmAddProposal">创建</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 提示词编辑对话框 -->
        <el-dialog
            v-model="pInputModel.dialogVisible"
            title="提示词编辑"
            width="880"
        >
            <div class="p-input-model-wrap">
                <div class="p-input-model-left">
                    <div class="sm-list">
                        <div class="sm-list-item" :class="{ active: pInputModel.active === item.id }" v-for="item in pInputModel.promptList" :key="item.id" @click="pInputModel.selectRecommendPrompt(item)">
                            <span class="sm-title">{{ item.name }}</span>
                            <span class="sm-desc">{{ item.content }}</span>
                        </div>
                    </div>
                </div>
                <div class="p-input-model-right">
                    <el-input v-model="pInputModel.form.content" type="textarea" :rows="20" maxlength="3000" show-word-limit placeholder="请输入提示词"/>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="pInputModel.cancelInputModel">取消</el-button>
                    <el-button type="success" @click="pInputModel.openPrompt">添加到提示词库</el-button>
                    <el-button type="primary" @click="pInputModel.confirmInputModel">应用</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 模板编辑对话框 -->
        <el-dialog
            v-model="pTemplateModel.dialogVisible"
            title="模板编辑"
            width="1000"
        >
            <div class="temp-model-wrap">
                <div class="temp-model-left">
                    <!-- <div class="search">
                        <el-input v-model="input1" style="width: 100%" placeholder="Please Input" :prefix-icon="Search" />
                    </div> -->
                    <div class="tab-list">
                        <div class="tab-list-item" :class="{ active: pTemplateModel.recommendTemplateType.typeActive === item.value }" v-for="item in pTemplateModel.tempTypeDict" :key="item.value" @click="pTemplateModel.selectRecommendTemplateType(item)">
                            <span class="tab-title">{{ item.label }}</span>
                        </div>
                    </div>
                </div>
                <div class="temp-model-right">
                    <div class="sub-topic-wrap" v-for="typeItem in pTemplateModel.recommendTemplateType.list" :key="typeItem.type">
                        <div class="sub-topic-wrap-title">{{ typeItem.type }}</div>
                        <div class="sub-topic-content">
                            <div class="st-list" >
                                <div class="st-item" v-for="item in typeItem.list" :class="{ active: pTemplateModel.recommendTemplateType.tempActive === item.id }" :key="item.id" >
                                    <div class="st-top">
                                        <div class="st-box">
                                            <img :src="item.thumbnail"/>
                                        </div>
                                    </div>
                                    <div class="st-bottom">
                                        <div class="st-title">
                                            <i class="title-icon"><el-icon class="title-icon" size="18" color="#409eff"><List /></el-icon></i>
                                            <span class="title-name">{{ item.name }}</span>
                                        </div>
                                    </div>
                                    <div class="hover-btn-wrap">
                                        <el-button class="new-icon" :icon="View" @click="tempView(item)"/>
                                        <el-button class="new-use" type="primary" @click="pTemplateModel.tempUse(item)">立即使用</el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="pTemplateModel.cancelTemplateModel">取消</el-button>
                    <el-button type="primary" @click="pTemplateModel.confirmTemplateModel">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog v-model="importModel.dialogVisible" title="导入方案" width="520">
            <el-form ref="importFormRef" :model="importModel.form" label-width="90px" :rules="proposalModel.proposalRules" :label-position="'top'">
                <el-form-item label="方案名称" prop="title">
                    <el-input v-model="importModel.form.title" maxlength="20" show-word-limit placeholder="请输入唯一的方案名称" />
                </el-form-item>
                <el-form-item label="所属行业" prop="industry">
                    <el-select v-model="importModel.form.industry" placeholder="请选择行业">
                        <el-option v-for="item in industryList" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择文件" prop="fileName">
                    <el-upload ref="uploadRef" class="upload" name="file" action="/api/import/word"
                        v-model:file-list="importModel.fileList" accept=".docx" limit="1" :auto-upload="false"
                        :on-change="importModel.handleChange" :on-remove="importModel.handleRemove"
                        :on-success="importModel.handleSuccess" :on-error="importModel.handleError"
                        style="width: 100%;">
                        <template #trigger>
                            <el-input v-model="importModel.form.fileName" readonly placeholder="点击选择文件" />
                        </template>

                        <template #tip>
                            <div class="el-upload__tip">
                                <p>支持格式：.docx</p>
                                <p>文件大小：不超过 10MB</p>
                            </div>
                        </template>
					</el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="importModel.cancelImport">取消</el-button>
                    <el-button type="primary" :loading="importModel.genLoading" @click="importModel.confirmAddImport">导入</el-button>
                </div>
            </template>
        </el-dialog>

        <!--新建文件夹对话框-->
        <el-dialog v-model="folderModel.dialogVisible" title="新建文件夹" width="420">
            <el-form ref="folderFormRef" :model="folderModel.form" :label-position="'top'">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="folderModel.form.name" maxlength="20" show-word-limit placeholder="请输入文件夹名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="folderModel.cancelFolder">取消</el-button>
                    <el-button type="primary" @click="folderModel.submitFolder">新建</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 重命名对话框 -->
        <el-dialog v-model="renameModel.dialogVisible" title="文档重命名" width="420">
            <el-form :model="renameModel.form" :label-position="'top'">
                <el-form-item label="文档名称" prop="name">
                    <el-input v-model="renameModel.form.name" maxlength="20" show-word-limit placeholder="请输入文档名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="renameModel.cancelRename">取消</el-button>
                    <el-button type="primary" @click="renameModel.submitRename">确定</el-button>
                </div>
            </template>
        </el-dialog>

        
        <!-- 提示词名称对话框 -->
        <el-dialog v-model="pInputModel.nameEdit" title="提示词编辑" width="420">
            <el-form :model="pInputModel.form" :label-position="'top'">
                <el-form-item label="提示词名称" prop="name">
                    <el-input v-model="pInputModel.form.name" maxlength="20" show-word-limit placeholder="请输入提示词名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="pInputModel.cancelPromptName">取消</el-button>
                    <el-button type="primary" @click="pInputModel.savePrompt">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <ViewTempModel ref="viewTempModelRef" @tempUse="viewTempUse"/>
    </div>
</template>

<script setup>
import { Search, Plus, HomeFilled, Menu, DeleteFilled, Folder, 
    CirclePlusFilled, View, Delete, Download, EditPen, List } from '@element-plus/icons-vue'
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { proposalApi } from '@/api/proposal.ts'
import { promptApi } from '@/api/prompt.ts'
import { foldersApi } from '@/api/folders'
import { templateApi } from '@/api/template'
import { industryList } from '@/constant/template'

import ViewTempModel from './template/ViewModel.vue'

const router = useRouter()
const projectTitle = import.meta.env.VITE_PROJECT_TITLE;

const toEditor = (id) => {
    window.open(`/editor/${id}`, '_blank');
}

// 工具箱 相关
const toolsModel = ref({
    tools: [
        {"name": "文档库", "icon": Folder, "path": "/layout/docs"},
        {"name": "知识库", "icon": Folder, "path": "/layout/knowledge"},
        {"name": "模板库", "icon": Folder, "path": "/layout/template"},
        {"name": "提示词库", "icon": Folder, "path": "/layout/prompt"},
    ],
    aiTools: [],
    toPage: (path) => { 
        window.open(path, '_blank');
    }
})

// -所属行业--------------------------------------------------------------------------------------
// const industryList = ref([
//     {
//         label: '环保行业',
//         value: '环保'
//     },
// ])
// ---------------------------------------------------------------------------------------

// 列表相关操作----
const tableModel = ref({
    tableData: [],
    pageParams: {
        current: 1,
        size: 20,
        total: 0
    },
    searchParams: {
        title: '',
        status: 1,
        folderId: ''
    },
    fetchProposals: async () => {
        try {
            const query = {
                current: tableModel.value.pageParams.current,
                size: tableModel.value.pageParams.size,
                ...tableModel.value.searchParams
            }
            const res = await proposalApi.getDocsList(query);
            tableModel.value.tableData = res.records;
            tableModel.value.pageParams.total = res.total;
        } catch (error) {
            ElMessage.error('获取方案列表失败');
        }
    },
    docDelete: (row) => {
        console.log(menuStatus.value)
        if(menuStatus.value == 'recycle'){
            proposalApi.deleteDocs(row.id).then(() => {
                ElMessage.success('删除成功');
                tableModel.value.fetchProposals();
            }).catch(() => {
                ElMessage.error('删除失败');
            });
            return
        }
        proposalApi.removeDocs(row.id).then(() => {
            ElMessage.success('删除成功');
            tableModel.value.fetchProposals();
        }).catch(() => {
            ElMessage.error('删除失败');
        });
    },
    docDownload: (row) => {
        window.open(`/api/docs/download?id=${row.id}`);
    },
    
})

// --文档方案相关-------------------------------------------------------------------------------------
const proposalFormRef = ref();
const proposalModel = ref({
    dialogVisible: false,
    mode: 'standard', // 模式：standard 或 template
    genLoading: false, // 生成按钮加载状态
    form: {
        title: '',
        industry: '',
        templateId: '',
        folderId: '',
        prompt: '',
        query: ''
    },
    proposalRules: {
        title: [
            { required: true, message: '方案名称不能为空', trigger: 'blur' },
            { max: 20, message: '方案名称不能超过20字', trigger: 'blur' }
        ],
        industry: [
            { required: true, message: '请选择方案类型', trigger: 'change' }
        ],
        templateId: [
            { required: true, message: '请选择方案模板', trigger: 'change' }
        ],
        prompt: [
            { required: true, message: '请填写提示词', trigger: 'blur' },
            { max: 3000, message: '方案Prompt不能超过3000字', trigger: 'blur' }
        ],
        fileName: [
            { required: true, message: '请选择文件', trigger: 'change' }
        ]
    },
    addProposal: (folderId) => {
        menuFolderId.value = folderId
        proposalModel.value.dialogVisible = true;
    },
    confirmAddProposal: () => {
        proposalFormRef.value.validate(async valid => {
            if (valid) {
                proposalModel.value.genLoading = true;

                proposalModel.value.form.folderId = menuFolderId.value;
                proposalApi.createDocs(proposalModel.value.form).then(res => {
                    console.log(res)
                    ElMessage.success('新建方案成功');
                    proposalModel.value.dialogVisible = false;
                    toEditor(res)
                }).catch(error => {
                    proposalModel.value.genLoading = false;
                    ElMessage.error('新建方案失败');
                    return;
                });
                
            }
        });
    },
    cancelProposal: () => {
        proposalModel.value.dialogVisible = false;
        proposalModel.value.form = {
            title: '',
            industry: '',
            templateId: '',
            folderId: '',
            prompt: '',
            query: ''
        }
        proposalFormRef.value.resetFields();
    },
    // 创建模式切换
    proposalModeChange: (value) => {
        if (value === 'standard') {
            proposalModel.value.form.template = '';
        }
    }
})


// ==提示词相关====================================
const promptInputRef = ref(null);
const pInputModel = ref({
    dialogVisible: false,
    promptList: [],
    active: '',
    form: {
        content: '',
        name:''
    },
    nameEdit: false,
    cancelInputModel: () => {
        pInputModel.value.dialogVisible = false;
        pInputModel.value.form.content = '';
    },
    confirmInputModel: () => {
        if (!pInputModel.value.form.content) {
            ElMessage.error('请输入提示词名称');
            return;
        }
        pInputModel.value.dialogVisible = false;

        proposalModel.value.form.prompt = pInputModel.value.form.content; // 将输入的提示词赋值给方案的prompt字段

        // 取消focus事件，避免输入框被遮挡
        if (promptInputRef.value) {
            promptInputRef.value.blur();
        }
    },
    listPrompt: () => {
        promptApi.list({}).then(res => {
            pInputModel.value.promptList = res;
        })
    },
    openPrompt: () => {
        if (!pInputModel.value.form.content) {
            ElMessage.error('请输入提示词');
            return;
        }
        pInputModel.value.nameEdit = true;
    },
    savePrompt: () => {
        console.log(pInputModel.value.form);
        promptApi.create({ content: pInputModel.value.form.content, name: pInputModel.value.form.name }).then(() => {
            ElMessage.success('提示词添加成功');
            pInputModel.value.nameEdit = false;
            pInputModel.value.form.content = '';
            pInputModel.value.listPrompt();
        }).catch(() => {
            ElMessage.error('提示词添加失败');
        });
    },
    selectRecommendPrompt: (item) => {
        pInputModel.value.form.content = item.content;
        pInputModel.value.active = item.id;
    },
    // 点击输入提示词方法
    inputHandleFocus: () => {
        pInputModel.value.listPrompt();
        pInputModel.value.dialogVisible = true;
    },
    cancelPromptName: () => {
        pInputModel.value.nameEdit = false;
        pInputModel.value.form.name = '';
    }
})

// ---模板相关------------------------------------------------------------------------------------
// 模板选择弹窗
const pTemplateSelectRef = ref(null);
const pTemplateModel = ref({
    dialogVisible: false,
    tempTypeDict: [
        { label: '全部', value: '全部' },
        ...industryList
    ],
    tempTypeList: [
        // { id: '1', name: '环保模板-1', industry: '1' },
        // { id: '2', name: '环保模板-2', industry: '1' },
        // { id: '3', name: '数据要素模板-1', industry: '2' },
        // { id: '4', name: '数据要素模板-2', industry: '2' },
        // { id: '5', name: '其他模板-1', industry: '3' },
        // { id: '6', name: '其他模板-2', industry: '3' }
    ],
    recommendTemplateType: {
        typeActive: '0',
        tempActive: '',
        rawList: [],
        list: []
    },
    // 使用模板，并关闭模板选择弹窗
    tempUse: (item) => {
        pTemplateModel.value.recommendTemplateType.tempActive = item.id; // 设置选中状态
        proposalModel.value.form.templateId = item.id; // 设置方案模板ID
        pTemplateModel.value.dialogVisible = false; // 关闭对话框
    },
    // 打开模板选择弹窗
    pTemplateHandleClick: () => {
        pTemplateModel.value.dialogVisible = true;

        pTemplateModel.value.queryTempList();
    },
    // 模板选择完成，点击确认按钮后的操作
    confirmTemplateModel: () => {
        if (!pTemplateModel.value.template) {
            ElMessage.error('请输入模板');
            return;
        }
        pTemplateModel.value.dialogVisible = false;
        pTemplateModel.value.template = pTemplateModel.value.template; 
    },
    // 取消模板选择
    cancelTemplateModel: () => {
        pTemplateModel.value.dialogVisible = false;
        pTemplateModel.value.template = '';
    },

    // 查询模板列表
    queryTempList: async () => {
        let list = await templateApi.getTempList({})
        pTemplateModel.value.tempTypeList = list;
    },
    groupTemplatesByType: (dict, templates) => {
        return dict
            .filter(item => item.value !== '全部') // 排除“全部”
            .map(item => ({
                type: item.label,
                typeValue: item.value,
                list: templates.filter(t => t.industry === item.value)
            }))
            .filter(group => group.list.length > 0) // 可选：去掉没有模板的类型
    },
    selectRecommendTemplateType: (item) => {
        pTemplateModel.value.recommendTemplateType.typeActive = item.value; // 设置选中状态

        if (pTemplateModel.value.recommendTemplateType.typeActive === '全部') {
            // 如果选择了“全部”，则显示所有模板
            pTemplateModel.value.recommendTemplateType.list = pTemplateModel.value.recommendTemplateType.rawList
                                                                .map(o => ({ type: o.type, list: [...o.list] }));
        } else {
            // 否则只显示选中类型的模板
            pTemplateModel.value.recommendTemplateType.list = pTemplateModel.value.recommendTemplateType.rawList
                                                                .filter(o => o.typeValue === pTemplateModel.value.recommendTemplateType.typeActive)
                                                                .map(o => ({ type: o.type, list: [...o.list] }));
        }
    },
})

watch(
    () => pTemplateModel.value.tempTypeList, 
    (newVal) => {
        pTemplateModel.value.recommendTemplateType.rawList = pTemplateModel.value.groupTemplatesByType(pTemplateModel.value.tempTypeDict, newVal);
        pTemplateModel.value.recommendTemplateType.list = pTemplateModel.value.recommendTemplateType.rawList.map(item => ({
            type: item.type,
            list: [...item.list]
        }));
    }, { immediate: true }
);
// ---------------------------------------------------------------------------------------




// 方案导入
// ---------------------------------------------------------------------------------------
const importFormRef = ref();
const uploadRef = ref();
const importModel = ref({
    dialogVisible: false,
    genLoading: false,
    fileList: [],
    form: {
        title: '',
        content: '',
        industry: '',
        templateId: '',
        folderId: '',
        prompt: '',
        fileName: ''
    },
    importProposal: () => {
        importModel.value.dialogVisible = true;
    },  
    cancelImport: () => {
        importModel.value.dialogVisible = false;
        importModel.value.form = {
            title: '',
            industry: '',
            templateId: '',
            folderId: menuFolderId.value,
            prompt: '',
            fileName: ''
        }
        importModel.value.resetFields();
    },
    handleChange: (file, fileList) => {
        console.log(file, fileList);
        importModel.value.form.fileName = file.name;
        importModel.value.fileList = fileList;
    },
    handleRemove: (file, fileList) => {
        importModel.value.fileList = [];
        importModel.value.form.fileName = "";
    },
    handleSuccess: (response, file, fileList) => {
        console.log('上传成功:', response);
        importModel.value.form.folderId = menuFolderId.value;
        importModel.value.form.content = response.html;
        proposalApi.createDocs(importModel.value.form).then(async res => {
            ElMessage.success('导入方案成功');
            importModel.value.dialogVisible = false;
            await tableModel.value.fetchProposals()
            toEditor(res)
        }).catch(error => {
            ElMessage.error('导入方案失败');
            importModel.value.genLoading = false;
            return;
        });
    },
    handleError: (error, file, fileList) => {
        console.error('上传失败:', error);
        ElMessage.error('文件上传失败');
    },
    confirmAddImport: async () => {
        await importFormRef.value.validate(valid => {
            if (valid) {
                importModel.value.genLoading = true;
                uploadRef.value.submit();
            }
        });
    },
})
// --导入结束-------------------------------------------------------------------------------------

// --菜单点击---------------------------------------------------------------
const menuStatus = ref('home');
const menuFolderId = ref('');
const clickMenu = (index) => {
    tableModel.value.searchParams.status = 1;
    tableModel.value.searchParams.folderId = '';
    if (index === 'home') {
        menuStatus.value = index;
        tableModel.value.searchParams.status = 1;
    } else if (index === 'recycle') {
        menuStatus.value = index;
        tableModel.value.searchParams.status = 0;
    } else {
        tableModel.value.searchParams.folderId = index.id;
        menuFolderId.value = index.id;
    }
    tableModel.value.fetchProposals(); 
}

// --文档目录-----------------------------------------------------------------------------
const folderList = ref([]);
const folderModel = ref({
    dialogVisible: false,
    folderProps: {
        children: 'children',
        label: 'name'
    },
    form: {
        name: '',
        pid: ''
    },
    addFolder: (folderId) => {
        console.log(folderId)
        folderModel.value.form.pid = folderId || 0;
        folderModel.value.dialogVisible = true;
    },
    cancelFolder: () => {
        folderModel.value.dialogVisible = false;
        folderModel.value.form = {
            name: ''
        }
    },
    submitFolder: async () => {
        if (!folderModel.value.form.name) {
            ElMessage.error('请输入文件夹名称');
            return;
        }
        const isExist = folderList.value.some(folder => 
            folder.name === folderModel.value.form.name || 
            (folder.children && folder.children.some(child => 
                child.name === folderModel.value.form.name
            ))
        );
        if (isExist) {
            ElMessage.error('已存在同名文件夹');
            return;
        }

        const res = await foldersApi.create(folderModel.value.form);
        
        folderModel.value.getFolderList()

        folderModel.value.dialogVisible = false;
        folderModel.value.form = {
            name: ''
        }
    },
    getFolderList: async () => {
        try {
            const res = await foldersApi.getList({});
            folderList.value = res;
        } catch (error) {
            ElMessage.error('获取文档目录失败');
        }
    },
    // 添加删除文件夹方法
    deleteFolder: async (folderId) => {
        try {
            await foldersApi.remove(folderId)
            folderModel.value.getFolderList()
        } catch (error) {
            console.error('删除文件夹失败:', error);
            ElMessage.error(error.response?.data || error.message || '删除失败');
        }
    }
});
// --文档目录结束-----------------------------------------------------------------------------

// --文档重命名-----------------------------------------------------------------------------
const renameModel = ref({
    dialogVisible: false,
    form: {
        name: '',
    },
    renameDoc: (row) => {
        renameModel.value.form.name = row.title;
        renameModel.value.form.id = row.id;
        renameModel.value.dialogVisible = true;
    },
    cancelRename: () => {
        renameModel.value.dialogVisible = false;
        renameModel.value.form = {
            name: '',
            id: ''
        }
    },
    submitRename: async () => {
        if (!renameModel.value.form.name) {
            ElMessage.error('请输入文档名称');
            return;
        }
        const isExist = tableModel.tableData.value.some(doc => 
            doc.title === renameModel.value.form.name && doc.id !== renameModel.value.form.id
        );
        if (isExist) {
            ElMessage.error('已存在同名文档');
            return;
        }

        try {
            await proposalApi.updateDocs(renameModel.value.form.id, { title: renameModel.value.form.name });
            ElMessage.success('文档重命名成功');
            renameModel.value.dialogVisible = false;
            tableModel.value.fetchProposals();
        } catch (error) {
            console.error('重命名失败:', error);
            ElMessage.error('文档重命名失败');
        }
    }
})
// --文档重命名-----------------------------------------------------------------------------



// ---------------------------------------------------------------------------------------
// 模板弹窗预览
const viewTempModelRef = ref()
const tempView = (item) => {
  viewTempModelRef.value.open(item)
}

// 预览弹窗组件-点击使用模板
const viewTempUse = (item) => {
    console.log(item, 'item')
}

// ---------------------------------------------------------------------------------------
onMounted(() => {
    tableModel.value.fetchProposals();
    folderModel.value.getFolderList();
});

// ---------------------------------------------------------------------------------------
</script>

<style lang="less">
:root{
  --desktop-layout-pc-min-width: 1128px;
  --sidebar-width: 244px;

  --bg-lv1-medium: #f3f5f7;
  --icon-strong: #464d5a;
  --border-weak: rgba(0, 0, 0, .04);
  --text-strong: rgba(0, 0, 0, .64);
}
.home-wrap{
  font-size: 16px;
  font-weight: 400;
  line-height: 22px;
  overflow: auto hidden;

  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100vh;
  overflow: hidden;
  overscroll-behavior: none;
  background-color: var(--bg-lv1-medium, #f3f5f7);
}

.desktop-layout-pc{
  color: rgba(0, 0, 0, .88);
  color: var(--text-ultrastrong, rgba(0, 0, 0, .88));
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: var(--desktop-layout-pc-min-width);

  .desktop-top-bar {
    display: flex;
    flex-shrink: 0;
    padding-right: 12px;
    position: relative;
  }

  .desktop-layout-inner-pc{
    display: flex;
    flex: 1 1;
    overflow: hidden;
  }
}

.user-name {
    vertical-align: 10px;
}
.nav-btn {
    margin-top: 20px;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding-left: 40px;
    padding-right: 40px;
    .btn {
        width: 100%;
        height: 35px;
        margin-bottom: 10px;
        margin-left: 0;
        margin-right: 0
    }
}
.nav-menu {
    background-color: inherit;
}

.icon {
    width: 1.3em; 
    height: 1.3em; 
    margin-right: 8px;
}

.m-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    border-bottom: 1px solid rgba(0, 0, 0,.04);
    border-bottom: 1px solid var(--border-weak, rgba(0, 0, 0,.04));
}
.m-body {
    .m-table{
        font-size: 13px;
    }
    .title {
        cursor: pointer;
        font-size: 14px;
        &:hover{
            color: #1890ff;
        }
    }
    height: 100%;
}
.b-body {
    display: flex;
    flex-direction: column;
    padding: 8px 0;
    .tools-panel{
        margin-bottom: 18px;
    }
    .tools-title{
        color: rgba(0, 0, 0, .64);
        color: var(--text-strong, rgba(0, 0, 0, .64));
        font-size: 12px;
        font-weight: 600;
        line-height: 16px;
        margin: 8px 16px 12px;
    }
    .tools{
        grid-gap: 8px;
        display: grid;
        gap: 8px;
        grid-template-columns: repeat(2, 1fr);
        padding: 0 12px;
        .tool-item{
            align-items: center;
            background-color: #f9fafb;
            background-color: var(--bg-lv4-weak, #f9fafb);
            border-radius: 4px;
            box-sizing: border-box;
            cursor: pointer;
            display: flex;
            overflow: hidden;
            padding: 8px 0 8px 16px;
            position: relative;

            &:hover{
                background-color: #f3f5f7;
            }
            
            span{
                color: rgba(0, 0, 0, .88);
                color: var(--text-ultrastrong, rgba(0, 0, 0, .88));
                font-size: 12px;
                line-height: 16px;
                text-align: center;
                white-space: nowrap;
            }
        }
    }
}



.desktop-sidebar{
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 500px;
  min-width: 244px;
  overflow: hidden;
  position: relative;
  -webkit-user-select: none;
  user-select: none;
}

.desktop-layout-inner-pc{
  .desktop-layout-sidebar-pc {
    flex-grow: 0;
    flex-shrink: 1;
    overflow: hidden;
    width: var(--sidebar-width);
  }
  .desktop-layout-main-pc {
    border: 1px solid rgba(0, 0, 0, .04);
    border: 1px solid var(--border-weak, rgba(0, 0, 0, .04));
    border-bottom: 0;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    flex-grow: 1;
    flex-shrink: 999999999;
    height: 100%;
    margin-right: 8px;
    min-width: 484px;
    overflow: hidden;
    width: -webkit-min-content;
    width: min-content;
    background-color: #fff;
  }
  .desktop-panel {
    border: 1px solid rgba(0, 0, 0, .04);
    border: 1px solid var(--border-weak, rgba(0, 0, 0, .04));
    border-bottom: 0;
    border-radius: 8px;
    border-bottom-left-radius: 0;
    flex-shrink: 0;
    margin-right: 12px;
    overflow: hidden;
    -webkit-user-select: none;
    user-select: none;
    width: 320px;
    background-color: #fff;
  }
}

.desktop-top-bar{
  .desktop-top-bar-left {
    align-items: center;
    display: flex;
    flex-grow: 0;
    flex-shrink: 1;
    height: 60px;
    width: var(--sidebar-width);
  }

  .desktop-top-bar-right {
    align-items: center;
    display: flex;
    flex-grow: 1;
    flex-shrink: 0;
    height: 60px;
    position: relative;
    min-width: 812px;
    z-index: 999;

    & > * {
      flex-shrink: 0;
      margin-right: 12px;
    }
  }

  .desktop-logo-pc{
    background-repeat: no-repeat;
    height: 24px;
    margin-left: 32px;
    flex-shrink: 0;
    margin-right: 16px;
    font-weight: 400;
    font-size: 24px;
  }

  .desktop-search-input-pc{
    flex: 1 1;
    margin-right: auto;
    max-width: 720px;
    min-width: 220px;

    .desktop-search-input {
      
    }

    .search-input{
      height: 40px;
    }
  }

  .desktop-top-bar-button {
    overflow: hidden;
    position: relative;
    align-items: center;
    border-radius: 4px;
    color: #464d5a;
    color: var(--icon-strong, #464d5a);
    display: flex;
    font-size: 12px;
    gap: 4px;
    height: 32px;
    line-height: 16px;
    padding: 0 4px;
  }

}

.proposal-mode-selector{
    width: 100%;
    margin-bottom: 18px;
    .el-radio-button{
        width: 50%;

        .el-radio-button__inner{
            width: 100%;
        }
    }
}

.p-input-model-wrap{
    display: flex;
    flex-direction: row;
    gap: 8px;
    overflow: hidden;
    height: 500px;

    .p-input-model-left{
        flex: 1;
        flex-basis: calc(1/3 * 100%);
        overflow-x: hidden;
        overflow-y: auto;
        padding: 0 12px 0 0;
    }

    .p-input-model-right{
        flex: 1;
        flex-basis: calc(2/3 * 100%) /* 66.6667% */;
        // border: 1px solid var(--border-weak, rgba(0, 0, 0, .04));
        overflow-y: auto;

        .el-textarea {
            height: 100%;
            .el-textarea__inner{
                height: 100%;

                &:hover,
                &:focus{
                    box-shadow: 0 0 0 1px #c0c4cc inset;
                }
            }
        }
    }
}


.sm-list{
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    font-size: 14px;
    line-height: 22px;
    
    .sm-list-item {
        position: relative;
        align-items: center;
        box-sizing: border-box;
        display: flex;
        flex-wrap: wrap;
        list-style: none;
        margin: 0;
        padding: 12px 12px;
        border-radius: 8px;
        cursor: pointer;

        &:not(.active)::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            height: 1px;
            background-color: rgba(87,104,161, .08);
        }

        &.active,
        &:hover{
            background-color: rgba(87,104,161, 0.08);
        }

        span{
            display: block;
            max-width: 100%;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }

        .sm-title{
            font-weight: 400;
            font-size: 14px;
            color: rgba(56,55,67,1);
        }
        .sm-desc{
            color: rgba(56,55,67,.64);
            font-size: 12px;
            margin-top: 4px;
        }
    }
}

.temp-model-wrap{
    display: flex;
    flex-direction: row;
    gap: 8px;
    overflow: hidden;
    height: 500px;
    border-top: 1px solid rgba(0,0,0,.04);
    border-bottom: 1px solid rgba(0,0,0,.04);

    .temp-model-left{
        display: flex;
        flex-direction: column;
        width: 200px;
        border-right: 1px solid rgba(0,0,0,.04);
        height: 100%;
    }

    .temp-model-right{
        flex: 1;
        overflow-y: auto;
        padding: 15px 0 0 10px;
    }
}

.temp-model-left{
    padding-right: 12px;
    .search {
        box-sizing: content-box;
        height: 36px;
        padding: 0 0 12px 0;
    }
    .tab-list{
        font-family: PingFang SC, Noto Sans SC, sans-serif;
        font-size: 14px;
        line-height: 22px;
    
        .tab-list-item {
            color: rgba(0,0,0,.88);
            cursor: pointer;
            font-size: 14px;
            font-weight: 400;
            height: 36px;
            line-height: 36px;
            opacity: 1;
            overflow: hidden;
            text-indent: 26px;
            text-overflow: ellipsis;
            white-space: nowrap;
    
            &.active,
            &:hover{
                background: rgba(51,77,102,.08);
                color: rgba(0,0,0,.88);
            }
    
            span{
                display: block;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
            }
        }
    }
}

.temp-model-right{
    &::-webkit-scrollbar{
      width:5px;
    }
    &::-webkit-scrollbar-track {
        border-radius: 2px;
    }

    &::-webkit-scrollbar-thumb {
        background-color: rgba(39, 39, 39, .1);
        border-radius: 10px;
    }

    &::-webkit-scrollbar-thumb:hover {
        // background-color: rgb(118, 113, 113);
    }



    .sub-topic-wrap{
        padding-bottom: 5px;
        .sub-topic-wrap-title {
            color: rgba(0,0,0,.88);
            font-size: 16px;
            margin-bottom: 5px;
        }
        .sub-topic-content{

        }
    }


    .st-list{
        grid-gap: 16px;
        align-items: start;
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        justify-content: space-between;
        padding: 0 0 15px;

        .st-item{
            position: relative;
            background: #fff;
            border: 1px solid rgba(0,0,0,.08);
            border-radius: 2px;
            box-shadow: 0px 1px 4px 0px rgba(0,0,0,.08);
            box-sizing: border-box;
            cursor: pointer;
            height: auto;
            opacity: 1;
            overflow: hidden;
            position: relative;
            width: 100%;
        }

        .st-top{
            padding: 12px 12px 0;
            .st-box{
                position: relative;
                border: 1px solid rgba(0,0,0,.04);
                border-radius: 2px;
                box-sizing: content-box;
                overflow: hidden;
                width: 100%;
                height: 98px;
                img{
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 100%;
                    height: 100%;
                }
            }
        }

        .st-bottom{
            display: flex;
            flex-direction: column;
            padding: 8px 10px;
            background: #fff;

            .st-title{
                display: flex;
                align-items: center;
                height: 20px;
                .title-icon{
                    height: 20px;
                    margin-right: 4px;
                    width: 20px;
                }
                .title-name{
                    color: rgba(0,0,0,.88);
                    font-size: 14px;
                    line-height: 20px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }
        }

        .st-item:hover {
            .hover-btn-wrap {
                opacity: 1;
                visibility: visible;
            }
        }

        .hover-btn-wrap{
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            padding: 0 24px;
            position: absolute;
            left: 0;
            bottom: 0;
            background: rgba(0, 0, 0, .64);
            transition: all .1s;
            cursor: auto;
            z-index: 1;
            opacity: 0;
            visibility: hidden;

            .new-icon{
                width: 32px;
            }
        }
    }
}

.menu-label{
    color: #303133;
}

.tree-menu{
    background: #f3f5f7;
    color: #303133;
    .el-tree-node {
        .el-tree-node__content{
            height: 45px;
            &:hover {
                background-color: rgb(235.9,245.3,255);
            }
            &:focus {
                background-color: rgb(235.9,245.3,255);
            }
        }
        &.is-current{
            &:not(.is-expanded) {
                color: var(--el-menu-active-color);
                // & > .el-tree-node__content{
                //     background: transparent;
                // }
                .tree-node-label{
                    color: var(--el-menu-active-color);
                }
            }
        }
    }
    .tree-node{
        display: flex;
        align-items: center;
        margin-left: -6px;
        .tree-node-label{
            color: #303133;
        }
    }
    
}
.el-sub-menu .el-icon{
    margin-right: 0;
    margin-left: 8px;
}
</style>